<template>
  <div class="multi-measure-input">
    <el-input
      v-for="(item, idx) in measureValues"
      :key="idx"
      v-model.number="item.value"
      type="number"
      size="mini"
      :placeholder="`第${idx+1}次`"
      :step="1 / Math.pow(10, precision || 1)"
      @input="handleInput"
      class="measure-input-item"
      :disabled="disabled"
    ></el-input>
  </div>
</template>

<script>
export default {
  name: 'MultiMeasureInput',
  props: {
    // 绑定值：数组格式 [{value: 数值}, ...]，长度与 multiMeasureCount 一致
    value: {
      type: Array,
      default: () => []
    },
    // 精度（保留几位小数）
    precision: {
      type: Number,
      default: 1
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 测次数量（控制输入框个数）
    multiMeasureCount: {
      type: [Number, String],
      default: 1,
      validator: (val) => {
        const num = Number(val);
        return !isNaN(num) && num >= 1 && num <= 10 && Number.isInteger(num); // 支持1-10次（可调整）
      }
    }
  },
  data() {
    return {
      measureValues: []
    };
  },
  watch: {
    multiMeasureCount: {
      immediate: true,
      handler() {
        this.initMeasureValues();
      }
    },
    value: {
      deep: true,
      handler(newVal) {
        this.measureValues = this.formatValues(newVal);
      }
    }
  },
  methods: {
    // 初始化测次输入值（根据 multiMeasureCount 生成）
    initMeasureValues() {
      const count = Number(this.multiMeasureCount);
      if (Array.isArray(this.value) && this.value.length === count) {
        this.measureValues = this.formatValues(this.value);
      } else {
        this.measureValues = Array.from({ length: count }, () => ({ value: '' }));
        this.$emit('input', this.measureValues);
      }
    },
    // 格式化输入值（确保为数字或空）
    formatValues(values) {
      if (!Array.isArray(values)) return [];
      const count = Number(this.multiMeasureCount);
      return values.slice(0, count).map(item => ({
        value: item?.value !== '' && !isNaN(item?.value) ? Number(item.value) : ''
      })).concat(
        Array.from({ length: Math.max(0, count - values.length) }, () => ({ value: '' }))
      );
    },
    // 输入变化时通知父组件
    handleInput() {
      this.$emit('input', this.measureValues);
      this.$emit('change', this.measureValues);
    }
  }
};
</script>

<style scoped>
.multi-measure-input {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 2px;
}
.measure-input-item {
  width: 100%;
  height: 32px;
}
</style>